<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'user');
define('DB_PASS', 'pass');
define('DB_SCHEMA', 'schema');


$mysql_connected = false;
$query_debug = false;

function ngdom_db_query($query) {
	global $mysql_connected;
	if (!$mysql_connected) {
		mysql_connect(DB_SERVER, DB_USER, DB_PASS);
		mysql_select_db(DB_SCHEMA);
		$mysql_connected = true;
	}
	
	if (func_num_args() > 1) {
		$args = array_slice(func_get_args(), 1);
		$args = @array_map(mysql_real_escape_string, $args);
		$query = call_user_func_array('sprintf', array_merge(array($query), $args)); 
	}
	
	global $query_debug;
	if ($query_debug) die($query);
	$result = mysql_query($query);
	
	if (!$result) return array('errno' => mysql_errno(), 'error' => mysql_error());
	if ($result === true) return mysql_affected_rows();
	return $result;
}
function ngdom_db_getval($query) {
	$args = func_get_args();
	$result = call_user_func_array('ngdom_db_query', $args);
	if (ngdom_is_db_error($result)) return $result;
	$array = mysql_fetch_array($result);
	return is_array($array) && count($array) > 0 ? array_shift($array) : null;
}
function ngdom_db_getrow($query) {
	$args = func_get_args();
	$result = call_user_func_array('ngdom_db_query', $args);
	if (ngdom_is_db_error($result)) return $result;
	return mysql_fetch_object($result);
}
function ngdom_db_getrows($query) {
	$args = func_get_args();
	$result = call_user_func_array('ngdom_db_query', $args);
	if (ngdom_is_db_error($result)) return $result;
	$rows = array();
	while ($row = mysql_fetch_object($result)) {
		$rows[] = $row;
	}
	return $rows;
}
function ngdom_is_db_error($result) {
	return is_array($result) && array_key_exists('errno', $result) && array_key_exists('error', $result);
}
?>